package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.stereotype.Repository;

import pojo.Info;
import dao.InfoDao;

@Repository(value="infoDao")
public class InfoDaoImpl implements InfoDao{
	@Resource(name="dataSource")
	private DataSource dataSource;

	@Override
	public Info addInfo(Info info) {
		String sql="insert into login (id,name,pwd,age) values (?,?,?,?)";
		Connection connection = null;
		PreparedStatement pst=null;
		int m=0;
		try {
			connection = dataSource.getConnection();
			info.setId(UUID.randomUUID().toString());
			pst = connection.prepareStatement(sql);
			pst.setString(1, info.getId());
			pst.setString(2, info.getName());
			pst.setString(3, info.getPwd());
			pst.setInt(4, info.getAge());
			m=pst.executeUpdate();
			return info;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} finally{
			close(connection, pst, null);
		}
	}

	@Override
	public Info findInfo(String name) {
		Connection connection = null;
		PreparedStatement pst = null;
		String sql = "select * from login where name=?";
		try {
			connection = dataSource.getConnection();
			pst=connection.prepareStatement(sql);
			pst.setString(1, name);
			ResultSet rs = pst.executeQuery();
			Info info = new Info();
			while(rs.next()){
				info.setId(rs.getString("id"));
				info.setName(rs.getString("name"));
				info.setPwd(rs.getString("pwd"));
				info.setAge(rs.getInt("age"));
			}
			return info;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} finally{
			close(connection, pst, null);
		}
	}
	
	
	private void close(Connection connection,PreparedStatement pst, ResultSet rs){
		try {
			if(rs!=null)
				rs.close();
			if(pst!=null)
				pst.close();
			if(connection!=null)
				connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
